package examples;

import org.apache.lucene.analysis.snowball.SnowballAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocCollector;
import org.apache.lucene.search.TopDocs;

import luceneqe.modelsIR.clauses.BM25MultiClauseQuery;
import luceneqe.modelsIR.clauses.SimilarityClauseBM25;
import luceneqe.utils.BM25Parameters;
import luceneqe.utils.CollectionStats;

public class BM25WithClause {

	public BM25WithClause() throws Exception {
	  
	  String query = "(house^1)";
	  String index = "../LuceneQE/examples/luceneqe-test-index";
	  String field = "text";
	 
	  CollectionStats.setAvgDocumentLength(598.0f);  
	  BM25Parameters.setB(0.67f);
	  BM25Parameters.setK1(3.8f);
	  SnowballAnalyzer analyzer = new SnowballAnalyzer("English");
	  String[] fields = { field }; 
	  QueryParser parser = new QueryParser(field, analyzer);    
	  IndexSearcher is = new IndexSearcher(index);
	  IndexReader   ir = is.getIndexReader();
	  
	  // Set up Similarity Function and Query to be claused:
	  is.setSimilarity(new SimilarityClauseBM25());  // Set Similarity Functin to BM25-Clauses
	  Query queryBM25 = new BM25MultiClauseQuery(parser.parse(query), // Build Strucured Query
	    fields, query);
	 
	  // Now search in the usual way:
	  TopDocCollector collector = new TopDocCollector(1000);
	  is.search(queryBM25, collector);
	  TopDocs resultados = collector.topDocs();
	 
	  ScoreDoc[] doc = resultados.scoreDocs;
	 
	  System.out.println("COLLECTION: "+index+"  ("+is.maxDoc()+")");
	  System.out.println("SIM: "+is.getSimilarity().getClass());
	  System.out.println("QUERY: <"+query+">");
	  System.out.println();
	  
	  
	  for (int n = 0; n < doc.length; n++) {
	   int d = doc[n].doc;
	   float s = doc[n].score;
	   Document document = ir.document(d);
	   System.out.println(n + ": ID=" + document.get("id")+ "s="+s);
	   System.out.println(is.explain(queryBM25, d).toString());
	  }
	 
	  is.close();
	  ir.close();
	 	 
	}
	
	public static void main(String[] args) {
		try {
			new BM25WithClause();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
